from django import template
from django.template.loader import get_template
from monkeystudio.blogs.models import Post, Comment

register = template.Library()

class CommentBoxContent( template.Node ):
  def __init__( self, post_id):
    self.postid = post_id

  def render(self, context ):
    postid = template.resolve_variable(self.postid, context)
    t = get_template('commentbox.html')
    context['postid'] = postid
    context['commentcount'] = Comment.objects.filter(post=postid).count()
    html = t.render( context )
    return html

def do_commentbox( parser, token):
  try:
    tag_name, post_id = token.split_contents()
  except ValueError:
    raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents)
  return CommentBoxContent( post_id )

class CommentListContent( template.Node ):
  def __init__( self, post_id):
    self.postid = post_id

  def render( self, context ):
    postid = template.resolve_variable(self.postid, context)
    t = get_template('commentlist.html')
    context['count'] = Comment.objects.filter(post=postid).count()
    context['commentlist'] = Comment.objects.filter(post=postid)
    html = t.render( context )
    return html

def do_commentlist( parser, token):
  try:
    tag_name, post_id = token.split_contents()
  except ValueError:
    raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents)
  return CommentListContent(post_id)
  

register.tag( 'commentbox', do_commentbox )
register.tag( 'commentlist', do_commentlist )
